package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
	@Autowired
	private CartMapper cartMapper;
	
	@Override
	public void clean() {
		LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
		
		wrapper.eq(UserHolder.getUser().getId() != null, Cart::getUserId, UserHolder.getUser().getId());
		
		cartMapper.delete(wrapper);
	}
	
	@Override
	public List<Cart> sub(Cart cart) {
		//购物车物品减少
		//查询购物车内物品,当该物品值少于1时删除该物品.
		LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
		//查找当前登录用户下的购物车中当前商品.
		wrapper.eq(UserHolder.getUser().getId() != null, Cart::getUserId,UserHolder.getUser().getId())
				.eq(Cart::getDishId,cart.getDishId());
		Cart carts = cartMapper.selectOne(wrapper);
		//如果当前商品的数量少于等于1,代表进行减法操作后当前商品数量将小于等于0,则进行删除操作,否则进行减法操作
		if (carts.getNumber() <= 1) {
			cartMapper.deleteById(carts);
		}else {
			carts.setNumber(carts.getNumber() - 1);
			cartMapper.updateById(carts);
		}
		return findList();
	}
	
	@Override
	public List<Cart> findList() {
		//查询购物车信息
		LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
		
		//查询购物车中内容
		wrapper.eq(Cart::getUserId, UserHolder.getUser().getId());
		List<Cart> cartList = cartMapper.selectList(wrapper);
		//数据返回
		return cartList;
	}
	
	@Override
	public Cart save(Cart cart) {
		//添加商品到购物车功能
		//判断商品是否存在
		//select * from shopping_cart where dish_id = #{菜品id} and userId = #{当前登录用户Id}
		LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(cart.getDishId()!=null,Cart::getDishId,cart.getDishId())
				.eq(cart.getSetmealId() != null,Cart::getSetmealId,cart.getSetmealId());
		wrapper.eq(UserHolder.getUser() != null,Cart::getUserId, UserHolder.getUser().getId());
		//查询最多返回一条购物车中商品
		Cart cartFromDB = cartMapper.selectOne(wrapper);
		
		if (cartFromDB != null) {
			//数据库中存在该商品
			//将该商品的number + 1
			cartFromDB.setNumber(cartFromDB.getNumber() + 1);
			cartMapper.updateById(cartFromDB);//向数据库中回写数据
			return cartFromDB;
		}else {
			//不存在
			//在数据库中插入该商品
			
			cart.setUserId(UserHolder.getUser().getId());
			cart.setNumber(1);
			cart.setCreateTime(new Date());
			cartMapper.insert(cart);
			return cart;
		}
	}
}
